/**
 * 通用网络请求工具
 * 支持增删改查和token拦截
 * @author software
 * @version 1.0.0
 */

// 基础配置
const baseConfig = {
	// 接口基础地址
	baseURL: 'https://software.jrauto.top:8061',
	// baseURL: 'http://127.0.0.1:8061',
	// 默认请求头
	header: {
		'content-type': 'application/json'
	},
	// 超时时间（毫秒）
	timeout: 10000,
	// 是否显示loading
	showLoading: true,
	// 错误提示信息
	errorMsg: '网络请求失败，请稍后重试',
	// 是否只返回data部分
	concise: true
}

// 请求拦截器
const requestInterceptors = []
// 响应拦截器
const responseInterceptors = []

class Request {
	constructor(config = {}) {
		this.config = {
			...baseConfig,
			...config
		}
		this.requestInterceptors = requestInterceptors
		this.responseInterceptors = responseInterceptors
	}

	/**
	 * 显示loading
	 */
	showLoading(title = '加载中...') {
		if (this.config.showLoading) {
			uni.showLoading({
				title,
				mask: true
			})
		}
	}

	/**
	 * 隐藏loading
	 */
	hideLoading() {
		if (this.config.showLoading) {
			uni.hideLoading()
		}
	}

	/**
	 * 显示提示信息
	 */
	showToast(title, icon = 'none', duration = 2000) {
		uni.showToast({
			title,
			icon,
			duration
		})
	}

	/**
	 * 获取token
	 */
	getToken() {
		return uni.getStorageSync('token') || ''
	}

	/**
	 * 处理请求配置
	 */
	processRequestConfig(config) {
		const token = "Bearer " + this.getToken()
		// 合并配置
		const finalConfig = {
			...this.config,
			...config,
			header: {
				...this.config.header,
				...config.header
			}
		}

		// 添加token到请求头
		if (token) {
			finalConfig.header.Authorization = token
		}

		// 处理URL
		if (!finalConfig.url.startsWith('http')) {
			finalConfig.url = this.config.baseURL + finalConfig.url
		}
		return finalConfig
	}

	/**
	 * 处理响应数据
	 */
	processResponse(response) {
		const {
			statusCode,
			data
		} = response
		// 处理HTTP状态码
		if (statusCode >= 200 && statusCode < 300) {
			// 成功响应
			if (this.config.concise) {
				return data
			}
			return response
		} else {
			// HTTP错误
			// throw new Error(`HTTP ${statusCode}: ${data?.message || '请求失败'}`)
			// HTTP错误
			throw new Error(`HTTP ${statusCode}: ${data?.message || '请求失败'}`)
		}
	}

	/**
	 * 处理错误
	 */
	handleError(error, config = {}) {
		// console.error('Request Error:', error)
		let errorMessage = this.config.errorMsg

		if (error.statusCode === 401) {
			errorMessage = '登录已过期，请重新登录'
			// 清除token并跳转到登录页
			uni.removeStorageSync('token')
			uni.removeStorageSync('user')
			uni.reLaunch({
				url: '/pages/login/login'
			})
		} else if (error.statusCode === 403) {
			errorMessage = '没有权限访问'
		} else if (error.statusCode === 404) {
			errorMessage = '请求的资源不存在'
		} else if (error.statusCode === 500) {
			errorMessage = '服务器内部错误'
		} else if (error.errMsg && error.errMsg.includes('timeout')) {
			errorMessage = '请求超时，请检查网络'
		} else if (error.errMsg && error.errMsg.includes('fail')) {
			errorMessage = '网络连接失败，请检查网络'
		}

		// 显示错误提示
		if (config.showError !== false) {
			this.showToast(errorMessage)
		}
		return Promise.reject(error)
	}

	/**
	 * 执行请求
	 */
	request(config) {
		// 处理请求配置
		const finalConfig = this.processRequestConfig(config)
		// 执行请求拦截器
		let promise = Promise.resolve(finalConfig)
		this.requestInterceptors.forEach(interceptor => {
			promise = promise.then(interceptor.fulfilled, interceptor.rejected)
		})

		// 发起请求
		promise = promise.then(config => {
			this.showLoading()
			return new Promise((resolve, reject) => {
				uni.request({
					...config,
					success: (response) => {
						this.hideLoading()
						resolve(response)
					},
					fail: (error) => {
						this.hideLoading()
						reject(error)
					}
				})
			})
		})

		// 执行响应拦截器
		this.responseInterceptors.forEach(interceptor => {
			promise = promise.then(interceptor.fulfilled, interceptor.rejected)
		})

		// 处理响应和错误
		return promise
			.then(response => this.processResponse(response))
			.catch(error => this.handleError(error, config))
	}

	/**
	 * GET请求
	 */
	get(url, data = {},config = {}) {
		return this.request({
			url,
			method: 'GET',
			data,
			...config
		})
	}

	/**
	 * POST请求
	 */
	post(url, data = {}, config = {}) {
		return this.request({
			url,
			method: 'POST',
			data,
			...config
		})
	}

	/**
	 * PUT请求
	 */
	put(url, data = {}, config = {}) {
		return this.request({
			url,
			method: 'PUT',
			data,
			...config
		})
	}

	/**
	 * DELETE请求
	 */
	delete(url, config = {}) {
		return this.request({
			url,
			method: 'DELETE',
			...config
		})
	}

	/**
	 * 文件上传
	 */
	upload(url, filePath, config = {}) {
		const finalConfig = this.processRequestConfig({
			url,
			filePath,
			name: 'file',
			...config
		})

		return new Promise((resolve, reject) => {
			this.showLoading('上传中...')
			uni.uploadFile({
				...finalConfig,
				success: (response) => {
					this.hideLoading()
					// console.log('原始返回内容：', response.data) // ← 加这一行
					try {
						const data = JSON.parse(response.data)
						resolve(data)
					} catch (error) {
						reject(error)
					}
				},
				fail: (error) => {
					this.hideLoading()
					this.handleError(error, config)
					reject(error)
				}
			})
		})
	}

	/**
	 * 添加请求拦截器
	 */
	addRequestInterceptor(fulfilled, rejected) {
		this.requestInterceptors.push({
			fulfilled,
			rejected
		})
	}

	/**
	 * 添加响应拦截器
	 */
	addResponseInterceptor(fulfilled, rejected) {
		this.responseInterceptors.push({
			fulfilled,
			rejected
		})
	}

	/**
	 * 移除请求拦截器
	 */
	removeRequestInterceptor(index) {
		if (this.requestInterceptors[index]) {
			this.requestInterceptors.splice(index, 1)
		}
	}

	/**
	 * 移除响应拦截器
	 */
	removeResponseInterceptor(index) {
		if (this.responseInterceptors[index]) {
			this.responseInterceptors.splice(index, 1)
		}
	}
}

// 创建默认实例
const request = new Request()

// 导出默认实例
export default request

// 导出Request类，方便创建新实例
export {
	Request,
	baseConfig
}

// 导出常用的请求方法
export const http = {
	get: (url, config) => request.get(url, config),
	post: (url, data, config) => request.post(url, data, config),
	put: (url, data, config) => request.put(url, data, config),
	delete: (url, config) => request.delete(url, config),
	upload: (url, filePath, config) => request.upload(url, filePath, config),
	request: (config) => request.request(config),
	addRequestInterceptor: (fulfilled, rejected) => request.addRequestInterceptor(fulfilled, rejected),
	addResponseInterceptor: (fulfilled, rejected) => request.addResponseInterceptor(fulfilled, rejected)
}

// export {
// 	baseConfig
// }

